<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { useSongAPI } from "@/services/song";
import { usePlaylistAPI } from "@/services/playlist";
import { IconPlay, IconHeart } from "@/components/icons";
import Navbar from "@/components/Navbar.vue";
import PlaylistCard from "@/components/PlaylistCard.vue";
import SongList from "@/components/SongList.vue";
import defaultMusicUrl from "@/assets/images/default_music.png";

const tabs = [
  { id: "songs", name: "歌曲", path: "/my-favorites" },
  // { id: "artists", name: "歌手", path: "/my-favorites" },
  { id: "playlists", name: "歌单", path: "/my-favorites" },
];

const activeTab = ref(tabs[0]);

const userStore = useUserStore();
const songAPI = useSongAPI();
const { getFavoritePlaylist } = usePlaylistAPI();
const favoriteSongs = ref<any[]>([]);
const favoritePlaylists = ref<any[]>([]);
const router = useRouter();

const loadFavoriteSongs = async () => {
  try {
    const songsResult = await songAPI.getFavoriteSongs(userStore.uid);
    const songItems = songsResult.data;
    favoriteSongs.value = songItems.map((item: any) => ({
      id: item.music.musicId,
      name: item.music.musicName,
      artist: item.music.musicAuthor,
      typeId: item.music.musicTypeId,
      url: item.music.musicUrl,
      cover: item.music.musicCoverUrl,
      length: item.music.musicLength,
      status: item.music.status,
      score: item.music.musicAverageScore,
      lyric: item.music.lyric,
      isFavorite: item.favorStatus,
    }));
  } catch (error) {
    console.error("Failed to load favorite songs:", error);
  }
};

const loadFavoritePlaylists = async () => {
  try {
    const response = await getFavoritePlaylist(userStore.uid);
    favoritePlaylists.value = response
      .filter((playlist: any) => playlist !== null)
      .map((playlist: any) => ({
        id: playlist.id,
        title: playlist.name,
        coverUrl: playlist.cover || "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250528224042.png",
        playCount: playlist.musicIds?.length || 0,
      }));
  } catch (error) {
    console.error("获取收藏歌单失败:", error);
  }
};

onMounted(() => {
  loadFavoriteSongs();
  loadFavoritePlaylists();
});

const goToPlaylist = (playlistId: number) => {
  router.push(`/playlist/${playlistId}`);
};

const favoriteArtists = ref(
  Array(20)
    .fill(null)
    .map((_, index) => ({
      id: index + 1,
      name: `音乐人 ${index + 1}`,
      avatar:
        "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250528231734.png",
      songCount: Math.floor(Math.random() * 100) + 50,
    }))
);
</script>

<template>
  <div class="p-4 max-w-7xl mx-auto">
    <h1 class="text-lg font-bold mb-4">我的收藏</h1>

    <Navbar v-model="activeTab" :items="tabs" />

    <!-- 收藏的歌曲 -->
    <div v-if="activeTab.id === 'songs'" class="mt-8">
      <SongList :songs="favoriteSongs" :show-header="false" />
    </div>

    <!-- 收藏的歌手 -->
    <div v-if="activeTab.id === 'artists'" class="mt-8">
      <el-table
        :data="favoriteArtists"
        style="width: 100%"
        :show-header="false"
      >
        <el-table-column>
          <template #default="{ row }">
            <router-link
              :to="`/artist/${row.id}`"
              class="flex items-center gap-4 flex-1 py-2"
            >
              <img
                :src="row.avatar"
                :alt="row.name"
                class="w-16 h-16 rounded-full object-cover"
              />
              <div>
                <h3 class="font-bold text-gray-900">{{ row.name }}</h3>
              </div>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 收藏的歌单 -->
    <div v-if="activeTab.id === 'playlists'" class="mt-8">
      <div class="grid grid-cols-5 gap-4">
        <PlaylistCard
          v-for="playlist in favoritePlaylists"
          :key="playlist.id"
          v-bind="playlist"
          @click="goToPlaylist(playlist.id)"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.el-table) {
  --el-table-border-color: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-hover-bg-color: #f9fafb;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__cell) {
  border-bottom: none;
}

:deep(.el-table__row) {
  border-radius: 8px;
}
</style>
